package org.csu.ssm_backend.web;

import cn.hutool.crypto.Mode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.csu.ssm_backend.domain.Account;
import org.csu.ssm_backend.service.AccountService;
import org.csu.ssm_backend.service.SendSmsService;
import org.csu.ssm_backend.service.util.MD5Util;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.net.http.HttpRequest;
import java.util.Objects;

@Controller
public class AccountController {

    String code = "";

    @Autowired
    AccountService accountService;

    @Autowired
    SendSmsService sendSmsService;

    /**
     * 初始页面默认为index，即登录页面
     * */
    @RequestMapping("/")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * 跳转到主页的页面
     * */
    @RequestMapping("/homePage")
    public ModelAndView change01(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();
        Account account = (Account) session.getAttribute("account");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("01");
        modelAndView.addObject("account",account);
        return modelAndView;
    }

    /**
     * 账号密码登录校验，成功则跳转，否则重新渲染
     * */
    @PostMapping("/accounts/index")
    public ModelAndView login(@RequestParam("username") String username,
                              @RequestParam("password") String password,
                              HttpServletRequest request){
        HttpSession session = request.getSession();
        ModelAndView modelAndView = new ModelAndView();
        Account account = accountService.getAccount(username,password);

        if (account != null){
            modelAndView.addObject("account",account);
            session.setAttribute("account",account);
            modelAndView.setViewName("MainPage");
        } else {
            modelAndView.addObject("errorMsg","用户名或密码错误!");
            modelAndView.setViewName("index");
        }

        return modelAndView;
    }

    /**
     * 发送手机验证码
     * */
    @GetMapping("/send")
    @ResponseBody
    public String sendCode(HttpServletRequest request){
        String phone = request.getParameter("phone");
        System.out.println(phone);
        // TODO:发送自己生成的验证码并将其赋值给this.code
        this.code = sendSmsService.getCode();
        System.out.println(this.code);
        try {
            // 发送手机验证码
            sendSmsService.sendMessage(phone,this.code);
            return "success!";
        } catch (Exception e){
            e.printStackTrace();
            return "send failed!";
        }
    }


    /**
     * 手机验证码登录校验
     * */
    @GetMapping("/accounts/index")
    @ResponseBody
    public ModelAndView phone_login(@RequestParam("user_phone")String phone,
                                    @RequestParam("user_check")String code,
                                    HttpSession session){
        ModelAndView mav = new ModelAndView();

        Account account = accountService.getAccountByPhone(phone);
        if (account == null){
            mav.addObject("loginMsg","您的手机号还没有绑定用户！");
            mav.setViewName("index");
        } else {
            if (Objects.equals(code, this.code)){
                // 验证码输入正确
                mav.addObject("account",account);
                session.setAttribute("account",account);
                mav.setViewName("MainPage");
            } else {
                // 验证码输出错误
                mav.addObject("loginMsg","验证码错误!");
                mav.setViewName("index");
            }
        }

        return mav;
    }

    /**
     * 注册校验，完成注册后跳转回到登录页面
     * */
    @PostMapping("/accounts/register")
    public ModelAndView sighUp(@RequestParam("user_name") String username,
                               @RequestParam("user_password") String password,
                               @RequestParam("user_email") String email){
        ModelAndView modelAndView = new ModelAndView();
        Account account = new Account();
        account.setUserid(username);
//        password = MD5Util.transformToMD5(password);
        account.setPassword(password);
        account.setEmail(email);
        accountService.insertAccount(account);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * 退出登录
     * */
    @GetMapping("/signOut")
    public ModelAndView signOut(){
        return new ModelAndView("index");
    }

    /**
     * 管理员用户个人信息主页
     * */
    @RequestMapping("/personInfoPage")
    public ModelAndView personPage(HttpSession session){
        Account account = (Account) session.getAttribute("account");
        System.out.println(account.getUserid() + " in person.");
        ModelAndView mav = new ModelAndView("04");
        session.setAttribute("account",account);
        mav.addObject("account",account);
        return mav;
    }

    /**
     * 管理员个人信息更新
     * */
    @PostMapping("/accounts/update")
    public ModelAndView personUpdate(
            @RequestParam("userid") String userid,
            @RequestParam("newUserid") String newUserid,
            @NotNull @RequestParam("newPassword") String newPassword,
            @RequestParam("repeatPassword") String repeatPassword,
            @RequestParam("firstName") String firstName,
            @RequestParam("lastName") String lastName,
            @RequestParam("email") String email,
            @RequestParam("phone") String phone,
            @RequestParam("address1") String address1,
            @RequestParam("address2") String address2,
            @RequestParam("city") String city,
            @RequestParam("zip") String zip,
            @RequestParam("country") String country,
            HttpSession session
    ){
        ModelAndView mav = new ModelAndView();
        Account account = (Account) session.getAttribute("account");
        Account newAccount = new Account();
        if (!newUserid.equals("")){
            newAccount.setUserid(newUserid);
        } else {
            newAccount.setUserid(userid);
        }

        mav.setViewName("04");

        if (newPassword.equals("")){
            newAccount.setPassword(account.getPassword());
        } else {
            if (!newPassword.equals(repeatPassword)){
                session.setAttribute("account",account);
                mav.addObject("account",account);
                mav.addObject("updateMsg","请输入相同的密码!");
                return mav;
            } else {
                newAccount.setPassword(newPassword);
            }
        }

        newAccount.setFirstName(firstName);
        newAccount.setLastName(lastName);
        newAccount.setEmail(email);
        newAccount.setPhone(phone);
        newAccount.setAddress1(address1);
        newAccount.setAddress2(address2);
        newAccount.setZip(zip);
        newAccount.setCity(city);
        newAccount.setCountry(country);

        accountService.updateAccount(newAccount);
        session.setAttribute("account",newAccount);
        mav.addObject("account",account);
        mav.addObject("updateMsg","修改成功!");
        return mav;
    }

}
